import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui';

//此处原子动画未完成  原因：无法导包  import 'package:image/image.dart' as gimage;
main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  ValueChanged<int> valueChanged = (value) {
    print("value $value");
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BodyWidget(),
    );
  }
}

class BodyWidget extends StatefulWidget {
  @override
  _BodyWidgetState createState() => _BodyWidgetState();
}

class _BodyWidgetState extends State<BodyWidget> with TickerProviderStateMixin {
  late AnimationController _animationController;

  int state = 0; // 0 合  1 展

  _anmiationSet(int code) {
    if (code == 0) {
      _animationController.forward();
    } else if (code == 1) {
      _animationController.reverse();
    }
  }

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(duration: Duration(milliseconds: 1000), vsync: this)
          ..addStatusListener((status) {
            if (status == AnimationStatus.forward) {
            } else if (status == AnimationStatus.reverse) {
            } else if (status == AnimationStatus.dismissed) {
              // _animationController.forward();
            } else if (status == AnimationStatus.completed) {
              // _animationController.reverse();
            }
          })
          ..addListener(() {
            setState(() {});
          });
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 300,
      height: 300,
      alignment: Alignment.center,
      child: Container(
        width: 300,
        height: 300,
        color: Colors.amberAccent,
        alignment: Alignment.center,
        child: Stack(alignment: Alignment.center, children: [
          StaggedAnimation(_animationController, _anmiationSet),
          Container(
            width: 30,
            height: 30,
            alignment: Alignment.center,
            padding: EdgeInsets.zero,
            margin: EdgeInsets.zero,
            decoration:
                BoxDecoration(color: Colors.black, shape: BoxShape.circle),
            child: TextButton(
              onPressed: () {
                if (_animationController.isAnimating) return;
                if (state == 0) {
                  _anmiationSet(0);
                  state = 1;
                } else {
                  _anmiationSet(1);
                  state = 0;
                }
              },
              child: Text(
                "${state == 0 ? "合" : "展"}",
                style: TextStyle(color: Colors.pink, fontSize: 12),
              ),
            ),
          )
        ]),
      ),
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class FlowItem extends StatefulWidget {
  String str;
  int index;
  ValueChanged<int> valueChanged;

  FlowItem(this.str, this.index, this.valueChanged);

  @override
  _FlowItemState createState() => _FlowItemState();
}

class _FlowItemState extends State<FlowItem> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 30,
      height: 30,
      alignment: Alignment.center,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      decoration: BoxDecoration(color: Colors.black, shape: BoxShape.circle),
      child: TextButton(
        onPressed: () {},
        child: Text(
          "${widget.str}",
          style: TextStyle(color: Colors.pink, fontSize: 12),
        ),
      ),
    );
  }
}

class MyInheritedWidget extends InheritedWidget {
  double spin; //旋转
  double office; //位移

  MyInheritedWidget(this.office, this.spin, {Key? key, required Widget child})
      : super(key: key, child: child);

  static MyInheritedWidget? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
  }

  @override
  bool updateShouldNotify(covariant InheritedWidget oldWidget) {
    return true;
  }
}

class StaggedAnimation extends StatelessWidget {
  List tagList = ["甲", "乙", "丙", "丁", "戊"];
  late Animation<double> controller;
  late Animation<double> spin; //旋转
  late Animation<double> office; //位移
  ValueChanged<int> valueChanged;

  StaggedAnimation(this.controller, this.valueChanged)
      : spin = Tween(begin: 0.0, end: 1.0).animate(
            CurvedAnimation(parent: controller, curve: Interval(0.5, 1)))
          ..addListener(() {}),
        office = Tween(begin: 0.0, end: 1.0).animate(
            CurvedAnimation(parent: controller, curve: Interval(0.0, 0.5)));

  @override
  Widget build(BuildContext context) {
    return MyInheritedWidget(
      office.value,
      spin.value,
      child: AnimatedBuilder(
          animation: controller,
          builder: (BuildContext context, Widget? child) {
            return Flow(
              delegate: MyFlowDelegate(
                  MyInheritedWidget.of(context)?.office ?? 0,
                  MyInheritedWidget.of(context)?.spin ?? 0),
              children: tagList.map((e) {
                return FlowItem(e, tagList.indexOf(e), valueChanged);
              }).toList(),
            );
          }),
    );
  }
}

class MyFlowDelegate extends FlowDelegate {
  double _value;
  double _radians;

  MyFlowDelegate(this._value, this._radians);

  @override
  bool shouldRepaint(covariant FlowDelegate oldDelegate) {
    return true;
  }

  @override
  void paintChildren(FlowPaintingContext context) {
    for (int i = 0; i < context.childCount; i++) {
      var y = 0 + sin((pi / 4 * (i) - pi / 2) * _radians) * 80;
      var x = _radians == 0
          ? 80.0 * _value
          : cos((pi / 4 * (i) - pi / 2) * _radians) * 80;
      context.paintChild(i,
          transform: Matrix4.translationValues(x + 135, y + 135, 0));
    }
  }
}

//原子动画层
class BitmapCopy extends StatelessWidget {

  Widget widget;
  GlobalKey _globalKey=GlobalKey();

  BitmapCopy(this.widget);

  @override
  Widget build(BuildContext context) {
     return GestureDetector(
       onTap: (){

       },
       child: RepaintBoundary(
          key: _globalKey,
          child: widget,
       ),
     );
  }
  //截图控件
  // Future _getImageInfo() async {
  //    RenderRepaintBoundary? findRenderObject =_globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
  //    var img = await findRenderObject!.toImage();
  //    var byteData =await img.toByteData(format: ImageByteFormat.png);
  //    var uint8List = byteData!.buffer.asUint8List();
  //    return gimage.decodeImage(uint8List);
  // }

}

